package com.xixisleep.yeojbackend.judge;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.xixisleep.yeojbackend.common.ErrorCode;
import com.xixisleep.yeojbackend.exception.BusinessException;
import com.xixisleep.yeojbackend.judge.codesandbox.CodeSandbox;
import com.xixisleep.yeojbackend.judge.codesandbox.CodeSandboxFactory;
import com.xixisleep.yeojbackend.judge.codesandbox.CodeSandboxProxy;
import com.xixisleep.yeojbackend.judge.codesandbox.model.ExecuteCodeRequest;
import com.xixisleep.yeojbackend.judge.codesandbox.model.ExecuteCodeResponse;
import com.xixisleep.yeojbackend.judge.strategy.JudgeContext;
import com.xixisleep.yeojbackend.model.dto.question.JudgeCase;
import com.xixisleep.yeojbackend.judge.codesandbox.model.JudgeInfo;
import com.xixisleep.yeojbackend.model.entity.Question;
import com.xixisleep.yeojbackend.model.entity.QuestionSubmit;
import com.xixisleep.yeojbackend.model.enums.QuestionSubmitStatusEnum;
import com.xixisleep.yeojbackend.service.QuestionService;
import com.xixisleep.yeojbackend.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class JudgeServiceImpl implements JudgeService{

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    @Value("${codesandbox.type:example}")
    private String type;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 根据题目提交id,拿到对应的题目，提交信息（包括代码，编程语言等）
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        // 如果不为等待状态
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中");
        }
        //3.更新判题（题目提交）的状态未”判题中“，防止重复执行
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        //4.调用沙箱，获取到执行结果
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();
        //获取输入用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutputList();
        //5. 根据沙箱执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCUEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }

        //在获取一次最新的状态
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        //根据判题结果，更新题目表中的accepted，
        String judgeInfoStr = questionSubmitResult.getJudgeInfo();
        JudgeInfo judgeInfoNew = JSONUtil.toBean(judgeInfoStr, JudgeInfo.class);
        if (judgeInfoNew.getMessage().equals("Accepted")){
            //根据判题结果，判断是否异步更新数据accepted，
            int acceptNum = question.getAcceptNum() + 1;
            question.setAcceptNum(acceptNum);
            boolean updateAcceptNum = questionService.updateById(question);
            if (!updateAcceptNum) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目通过数更新错误");
            }
        }

        return questionSubmitResult;
    }
}
